package com.definesys.smecrailtransit.service.LogService;

import android.content.Context;
import android.util.Log;


import com.definesys.smecrailtransit.SmecManager.SmecRealm.RealmManager;
import com.definesys.smecrailtransit.SmecManager.SmecRetrofit.BaseSubscriber;
import com.definesys.smecrailtransit.SmecManager.SmecRetrofit.HttpResult;
import com.definesys.smecrailtransit.base.SmecBasePresenter;
import com.definesys.smecrailtransit.utils.CommonUtils;


import java.util.AbstractList;
import java.util.ArrayList;

import java.util.List;

import io.realm.Realm;
import io.realm.RealmObject;
import io.realm.RealmResults;

import rx.Observable;


import static com.definesys.smecrailtransit.service.LogService.AbnormalCollection.submitStatus_ING;
import static com.definesys.smecrailtransit.service.LogService.AbnormalCollection.submitStatus_OVER;
import static com.definesys.smecrailtransit.service.LogService.AbnormalCollection.submitStatus_READY;

/**
 * Created by xupeizuo on 2017/3/2.
 */

public class LogServicePresenter extends SmecBasePresenter implements LogSericeContract {

    public Realm realm;

    public LogServicePresenter(Context mContext) {
        super(mContext);
        realm = RealmManager.getInstance().getRealm();
    }

    @Override
    public void uploadDataToServer(final ExceptionDto exceptionDto) {

        Log.e("当前上传操作线程是",Thread.currentThread().getName());

        if(exceptionDto == null || !CommonUtils.notEmpty(exceptionDto.getCrashLog())){
            return;
        }
        Observable<HttpResult<Object>> observable= smecRailService.sendExceptionMsgToServer(exceptionDto);

        schedulerThread(observable).subscribe(new BaseSubscriber<HttpResult<Object>>() {

            @Override
            public void onError(Throwable e) {
                changeStatus(exceptionDto);
            }

            @Override
            public void onNext(HttpResult<Object> objectHttpResult) {
                if(objectHttpResult.getCode().equals("SUCCESS")){
                    deteleDataFromRealm(exceptionDto);
                }else {
                    changeStatus(exceptionDto);
                }
            }
        });
    }

    @Override
    public ExceptionDto getDataFromRealm() {
        ExceptionDto exceptionDto=new ExceptionDto();
        RealmResults<ExceptionBean> exceptionBeanRealmResults=(RealmResults<ExceptionBean>)findAll(ExceptionBean.class);

        if(notEmpty(exceptionBeanRealmResults)){
            List<ExceptionBean> tempArrayList = Realm.getDefaultInstance().copyFromRealm(exceptionBeanRealmResults);
            if(realm.isInTransaction()){
                ArrayList<ExceptionBean> exceptionBeanArrayList=new ArrayList<>();
                for(ExceptionBean exceptionBean: tempArrayList){
                    exceptionBean.setSubmitStatus(submitStatus_ING);
                    exceptionBeanArrayList.add(exceptionBean);
                }
                exceptionDto.setCrashLog(exceptionBeanArrayList);
            }else {
                realm.beginTransaction();
                ArrayList<ExceptionBean> exceptionBeanArrayList=new ArrayList<>();
                for(ExceptionBean exceptionBean: tempArrayList){
                    exceptionBean.setSubmitStatus(submitStatus_ING);
                    exceptionBeanArrayList.add(exceptionBean);
                }
                exceptionDto.setCrashLog(exceptionBeanArrayList);
                realm.commitTransaction();
            }
            saveOrUpdateBatch(exceptionBeanRealmResults);
        }
        return exceptionDto;
    }

    @Override
    public void deteleDataFromRealm(ExceptionDto exceptionDto) {
        deleteObject(exceptionDto,ExceptionBean.class);
    }

    public static boolean notEmpty(AbstractList<?> T){

        return T != null && !T.isEmpty();
    }

    /**
     * 查询所有
     *
     * @return 返回结果集合
     */
    public RealmResults<? extends RealmObject> findAll(Class<? extends RealmObject> clazz) {
        return realm.where(clazz).contains("submitStatus",submitStatus_READY)
                .findAll();
    }

    /**
     * 删除日志状态为上传完成的realm数据
     * @param exceptionDto
     * @param clazz
     * @return
     */
    public boolean deleteObject(ExceptionDto exceptionDto,Class<? extends RealmObject> clazz){

        try {
            ArrayList<ExceptionBean> list=exceptionDto.getCrashLog();
            if(notEmpty(list)){
                if(!realm.isInTransaction()){
                    realm.beginTransaction();
                }
                for(ExceptionBean e1: list){
                    e1.setSubmitStatus(submitStatus_OVER);
                }
                realm.copyToRealmOrUpdate(list);

                RealmResults<ExceptionBean> e=(RealmResults<ExceptionBean>)realm.where(clazz).contains("submitStatus",submitStatus_OVER).findAll();
                e.deleteAllFromRealm();
                realm.commitTransaction();
            }
            return true;
        }catch (Exception e){
            e.printStackTrace();
            realm.cancelTransaction();
            AbnormalCollection.getAbnormalCollection().saveExceptionMsg(e,AbnormalCollection.EXCEPTION_TYPE_THROW_E);
            return false;
        }
    }

    /**
     * 网络异常时 即日志上传失败时将日志状态改为 submitStatus_READY
     * @param exceptionDto
     */
    public void changeStatus(ExceptionDto exceptionDto){

        try {
            Log.e("即日志上传失败时将日志状态改为","");
            ArrayList<ExceptionBean> list=exceptionDto.getCrashLog();
            if(notEmpty(list)){
                if(!realm.isInTransaction()){
                    realm.beginTransaction();
                }
                for(ExceptionBean e1: list){
                    e1.setSubmitStatus(submitStatus_READY);
                }
                realm.copyToRealmOrUpdate(list);
                realm.commitTransaction();
            }
        }catch (Exception e){
            e.printStackTrace();
            realm.cancelTransaction();
            AbnormalCollection.getAbnormalCollection().saveExceptionMsg(e,AbnormalCollection.EXCEPTION_TYPE_THROW_E);
        }
    }

    /**
     * 批量添加或者修改
     * @param list
     * @return 全部保存成功 或 全部失败
     */
    public boolean saveOrUpdateBatch(List<? extends RealmObject> list) {
        try {
            if(realm.isInTransaction()){
                realm.copyToRealmOrUpdate(list);
            }else {
                realm.beginTransaction();
                realm.copyToRealmOrUpdate(list);
                realm.commitTransaction();
            }
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            realm.cancelTransaction();
            return false;
        }
    }
}
